using Dapper;
using MediatR;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Write.Api.Application.Command.ERP.SalesManagement.H;
using System.Data;
using static RBAC.ErrorCode.APIEnums;

namespace RBAC.Write.Api.Application.Handler.ERP.SalesManagement
{
    /// <summary>
    /// 逻辑删除 发货通知单（Delivery_notice.IsDeleted = true）
    /// </summary>
    public class DeleteDeliveryNoticeHandler : IRequestHandler<DeleteDeliveryNoticeCommand, APIResult<bool>>
    {
        private readonly IDbConnectionFactory _dbConnectionFactory;

        public DeleteDeliveryNoticeHandler(IDbConnectionFactory dbConnectionFactory)
        {
            _dbConnectionFactory = dbConnectionFactory;
        }

        public async Task<APIResult<bool>> Handle(DeleteDeliveryNoticeCommand request, CancellationToken cancellationToken)
        {
            IDbConnection? conn = null;
            IDbTransaction? tran = null;

            try
            {
                conn = _dbConnectionFactory.CreateConnection();
                tran = conn.BeginTransaction();

                // 1) 校验是否存在且未删除
                var exists = await conn.QueryFirstOrDefaultAsync<int>(
                    "SELECT COUNT(1) FROM Delivery_notice WHERE Id = @Id AND IsDeleted = 0",
                    new { Id = request.Id }, tran);

                if (exists <= 0)
                {
                    tran.Rollback();
                    return new APIResult<bool> { Code = Error, Msg = "单据不存在或已删除", Data = false };
                }

                // 2) 逻辑删除
                var rows = await conn.ExecuteAsync(
                    "UPDATE Delivery_notice SET IsDeleted = 1 WHERE Id = @Id",
                    new { Id = request.Id }, tran);

                if (rows <= 0)
                {
                    tran.Rollback();
                    return new APIResult<bool> { Code = Error, Msg = "删除失败", Data = false };
                }

                // 3) 同步逻辑删除明细表：根据 Delivery_notice_id
                await conn.ExecuteAsync(
                    "UPDATE Delivery_notice_item SET IsDeleted = 1 WHERE Delivery_notice_id = @Id",
                    new { Id = request.Id }, tran);

                tran.Commit();
                return new APIResult<bool> { Code = Success, Msg = "删除成功", Data = true };
            }
            catch (Exception ex)
            {
                try { tran?.Rollback(); } catch { }
                return new APIResult<bool> { Code = Error, Msg = $"删除异常: {ex.Message}", Data = false };
            }
            finally
            {
                try { tran?.Dispose(); } catch { }
                try { conn?.Dispose(); } catch { }
            }
        }
    }
}
